import { BlockLoading } from "@/Loading/BlockLoading";
import { useMounted } from "@/utils/hooks/useMounted";
import React, { forwardRef, useCallback, useState } from 'react';

export interface InfiniteScrollerProps {
  className?: string;
  hasMore?: boolean;
  loadMore?: (() => Promise<unknown>) | ((stopLoading?: () => void) => void);
  skipLoadOnMount?: boolean;
  useWindow?: boolean;
  loader?: React.ReactNode;
  children?: React.ReactNode;
  threshold?: number;
}

const DEFAULT_LOADER = <BlockLoading height={60} loading icon="circle"/>;

export const InfiniteScroller = forwardRef<
  HTMLDivElement,
  InfiniteScrollerProps
  >(
  ({
    hasMore = false,
    loadMore,
    skipLoadOnMount,
    useWindow = false,
    loader = DEFAULT_LOADER,
    threshold = 1,
    className,
    children,
  },ref)=>{
    const [loading,setLoading] = useState(false);
    const mounted = useMounted();

    const stopLoading = useCallback(() => {
      if (mounted.current) {
        setLoading(false);
      }
    }, [mounted]);

    const load = useCallback(() => {
      if (typeof loadMore !== 'function') {
        return;
      }

      setLoading(true);
      if (loadMore.length > 0) {
        loadMore(stopLoading);
      } else {
        (loadMore as () => Promise<unknown>)().then(stopLoading, stopLoading);
      }
    }, [loadMore, stopLoading]);

    const onEnter = useCallback(
      (data: ))
  }
)

InfiniteScroller.displayName = 'InfiniteScroller';

export default InfiniteScroller;
